'''

Case Type： 数据库系统
Case Name： 套接字文件权限异常恢复，主备切换
Create At:  2020/07/27
@zou_jialiang0505328126
Descption:  1. 获取套接字文件路径
2. 获取套接字文件名
3. 修改套接字文件权限为不可读不可写
4. 连接数据库
5. 运行tpcc指令
6. 恢复socket文件权限
7. 连接数据库
8. 主备切换，备机执行
新主节点执行以下指令刷新：
9. 查看主备角色
10. 连接数据库
11. 切换后主节点运行tpcc指令


history：
created： 2020/07/27  created by @wan005
modified: 2020/9/28 n@ningyali   修改此类断言self.assertTrue(socket_connectMsg.find('') > -1)为此类self.assertEqual(socket_connectMsg, '')
'''
import os
import unittest
from yat.test import Node
import time
from yat.test import macro
import sys

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from testcase.utils.CommonSH import *

logger = Logger()
common = Common()
Constant = Constant()


class StopImmediate(unittest.TestCase):
    dbPrimaryUserNode = Node(node='PrimaryDbUser')
    dbPrimaryRootNode = Node(node='PrimaryRoot')
    DB_INSTANCE_PATH = macro.DB_INSTANCE_PATH
    DB_ENV_PATH = macro.DB_ENV_PATH
    GS_CTL_STOP_SUCCESS_MSG = Constant.GS_CTL_STOP_SUCCESS_MSG
    STANDBY_NORMAL = Constant.STANDBY_NORMAL
    PRIMARY_NORMAL = Constant.PRIMARY_NORMAL
    START_SUCCESS_MSG = Constant.START_SUCCESS_MSG
    TPCC_SUCCESS_MSG = Constant.TPCC_SUCCESS_MSG
    RESTART_SUCCESS_MSG = Constant.RESTART_SUCCESS_MSG
    SWITCHOVER_SUCCESS_MSG = Constant.SWITCHOVER_SUCCESS_MSG
    TPCC_PATH = macro.TPCC_PATH
    file_name = ''
    primary_sh = CommonSH('PrimaryDbUser')
    standby_1_sh = CommonSH('Standby1DbUser')
    standby_2_sh = CommonSH('Standby2DbUser')
    dbStandby1UserNode = Node(node='Standby1DbUser')
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        logger.info("-----------this is setup-----------")
        logger.info('------------Opengauss_Reliability_Dbsys_Case166.py start------------')

    def test_stop_immediate(self):
        time.sleep(30)
        logger.info("----------------------get socket file path--------------")
        sql = "show unix_socket_directory"
        getfilepathMsg = self.primary_sh.executDbSql(sql)
        logger.info(getfilepathMsg)
        file_path = getfilepathMsg.split('\n')[2]
        logger.info(file_path)

        logger.info("----------------------get socket file name--------------")
        get_file_list_cmd = f'ls -a {file_path}'
        logger.info(get_file_list_cmd)
        file_list = self.dbPrimaryUserNode.sh(get_file_list_cmd).result()
        logger.info(file_list)
        socket_file_name = ''
        for file in file_list.split():
            logger.info(file)
            if (self.dbPrimaryUserNode.db_port not in file) or ('lock' in file):
                pass
            else:
                socket_file_name = file
        logger.info(socket_file_name)
        self.file_name = file_path + "/" + socket_file_name
        logger.info("------------------modify file permission----------------------")
        deleteCmd = f'chmod 000 {self.file_name}'
        self.dbPrimaryUserNode.sh(deleteCmd).result()
        logger.info(deleteCmd)

        logger.info("----------------------connect opengauss----------------------")
        no_socket_connect_msg = self.primary_sh.nosocketConnect()
        logger.info(no_socket_connect_msg)
        self.assertEqual(no_socket_connect_msg, '')

        socket_connect_msg = self.primary_sh.socket_connect(file_path)
        logger.info(socket_connect_msg)
        self.assertIn(Constant.FAILED_CONNECT_DB, socket_connect_msg)

        logger.info("---------------------start TPCC----------------------")
        tpcc_result = common.startTPCC(self.dbPrimaryRootNode, self.TPCC_PATH)
        logger.info('-------------' + tpcc_result + '-----------------------')
        logger.info(tpcc_result)
        self.assertTrue(tpcc_result.find(self.TPCC_SUCCESS_MSG) > -1)

        logger.info("------------------------recover socket file------------------")
        recover_cmd = f'chmod 700 {self.file_name}'
        logger.info(recover_cmd)
        self.dbPrimaryUserNode.sh(recover_cmd)

        logger.info("----------------------connect opengauss----------------------")
        no_socket_connect_msg = self.primary_sh.nosocketConnect()
        logger.info(no_socket_connect_msg)
        self.assertEqual(no_socket_connect_msg, '')

        socket_connect_msg = self.primary_sh.socket_connect(file_path)
        logger.info(socket_connect_msg)
        self.assertEqual(socket_connect_msg, '')

        # 校验刷脏页是否完成
        logger.info('校验刷脏页是否完成')
        dirty_page_finshed_flag = self.primary_sh.check_whether_remain_dirty_page()
        self.assertTrue(dirty_page_finshed_flag)

        # 校验备机是否完成数据同步
        logger.info('校验备机是否完成数据同步')
        flag_1 = self.standby_1_sh.check_data_consistency()
        self.assertTrue(flag_1)
        flag_2 = self.standby_2_sh.check_data_consistency()
        self.assertTrue(flag_2)

        logger.info("-----------switchover standby1-----------")
        switchoverCmd = '''
        source {source_path};
        gs_ctl switchover  -D {DN_PATH} -m fast;
        gs_om -t refreshconf'''.format(source_path=self.DB_ENV_PATH, DN_PATH=self.DB_INSTANCE_PATH)
        switchoverMsg = self.dbStandby1UserNode.sh(switchoverCmd).result()
        logger.info(switchoverMsg)
        self.assertTrue(switchoverMsg.find(self.SWITCHOVER_SUCCESS_MSG) > -1)

        logger.info("-----------check opengauss status-----------")
        checkCmd = '''
            source {source_path};
            gs_om -t status --detail'''.format(source_path=self.DB_ENV_PATH)
        checktMsg = self.dbPrimaryUserNode.sh(checkCmd).result()
        logger.info(checktMsg.split('\n'))
        self.assertTrue(checktMsg.find(self.PRIMARY_NORMAL) > -1 and checktMsg.find(self.STANDBY_NORMAL) > -1)

        logger.info("----------------------connect opengauss----------------------")
        no_socket_connect_msg = self.primary_sh.nosocketConnect()
        logger.info(no_socket_connect_msg)
        self.assertEqual(no_socket_connect_msg, '')

        socket_connect_msg = self.primary_sh.socket_connect(file_path)
        logger.info(socket_connect_msg)
        self.assertEqual(socket_connect_msg, '')

    def tearDown(self):
        logger.info('----------------this is tearDown-----------------------')
        logger.info("------------------------recover socket file------------------")
        recoverCmd = f'chmod 700 {self.file_name}'
        logger.info(recoverCmd)
        self.dbPrimaryUserNode.sh(recoverCmd)
        logger.info("-----------switchover primary-----------")
        switchoverCmd = '''
        source {source_path};
        gs_ctl switchover  -D {DN_PATH} -m fast;
        gs_om -t refreshconf'''.format(source_path=self.DB_ENV_PATH, DN_PATH=self.DB_INSTANCE_PATH)
        switchoverMsg = self.dbPrimaryUserNode.sh(switchoverCmd).result()
        logger.info(switchoverMsg)
        self.assertIn(self.SWITCHOVER_SUCCESS_MSG, switchoverMsg)
